from fastapi import APIRouter, Depends, Request
from app.schema.sys.user import UserLogin
from utils.response import success, fail
from sqlalchemy.orm import Session
from utils.database import get_db
from utils.redis import RedisUtil
from app.model import AuthModel
from app.log import Log
import uuid, json

authController = APIRouter()

@authController.post("/login")
# @Log(title="用户xxxx登录系统", oper_type="用户登录")
async def do_login(
    req: Request,
    loginInfo:UserLogin, 
    db: Session = Depends(get_db)
):
    # step1 验证用户名密码是否正确
    res = AuthModel.login(
        loginInfo.username,
        loginInfo.password,
        db
    )

    if res is not None:
        #登陆成功
        # step2 生成token
        token = str(uuid.uuid4())

        user_id = res.user_id

        # print(json.dumps(res.__dict__))
        await RedisUtil.set_data(req.app, token, str(user_id))
        # req.app

        # step3 返回token
        return success("登陆成功", token)
    else:
        return fail("用户名或者密码错误")


